<?php



namespace app\index\controller;



use app\data\controller\store\GoodsCate;

use app\data\model\GoodsAttribute;

use app\data\model\GoodsAttributeRelations;
use app\data\model\GoodsAttributeValue;
use app\data\model\GoodsCate as ModelGoodsCate;
use app\data\model\GoodsModels;

use app\data\model\ShopGoodsCate;

use app\data\model\StoreGoods;

use app\index\controller\Custom;

use think\admin\Controller;

use think\facade\Db;

use think\facade\Route;





/**

 * Class Index

 * @package app\index\controller

 */

class Article extends Controller

{

    public function initialize()

    {

        //检测用户登陆状态

        $userID = $this->app->session->get('uid');

        $userInfo = $this->app->db->name('DataUser')->where('id', $userID)->find();

        $this->assign('userInfo', $userInfo);

        $this->assign('is_login',$this->app->session->get('uid') ? true : false);



        /* 定义全局函数 */

        $GLOBALS['function'] = new \app\index\controller\Custom($this->app);

        $this->assign('function', new \app\index\controller\Custom($this->app));



        /* 定义商城全局函数 */

        $GLOBALS['shop'] = new \app\index\controller\Customshop($this->app);

        $this->assign('shop', new \app\index\controller\Customshop($this->app));





        $config = $GLOBALS['function']->getConfig();      //获得网站配置

        $this->assign('config', $config);



        //加载语言包

        $langGet = $this->request->param('lang');

        if (empty($langGet)) {

            $this->app->session->set('lang', 'cn');

        } else {

            $this->app->session->set('lang', $langGet);

        }

        $lang = [];

        $langSession = $this->app->session->get('lang');

        include "public/lang/files/" . $langSession . ".php";

        $this->assign('lang', $lang);

        $this->assign('langSession', $langSession);



        //获取语言包列表

        $files = scandir($_SERVER["DOCUMENT_ROOT"] . "/public/lang/files/");

        $LanguageFilesList = [];

        // 读取指定目录下的所有文件

        foreach ($files as $key => $value) {

            if ($value == "." || $value == "..") {

            } else {

                $languageName = substr($value, 0, strrpos($value, "."));

                $LanguageFilesList[$key] = $languageName;

            }

        }

        $LanguageFilesList = array_values($LanguageFilesList);

        $this->assign('languagesList', $LanguageFilesList);



        //顶部自定义导航

        $nav = $GLOBALS['function']->getAllCat();      //获得网站导航

        $this->assign('nav', $nav);



        /*Banner轮播图*/

        $bannerArr = $GLOBALS['function']->sliderPictures(4);   //sliderPictures()里的数值去查看system_data数据表里name为对应位置，如首页轮播sliderHomePage所在的id

        $this->assign('banner', $bannerArr);



        //获得内容模型列表(用于搜索功能)

        $this->assign('modelList', $GLOBALS['function']->getModelList());

    }



    public function index()

    {

        //        $this->redirect(sysuri('admin/login/index'));

        //        $db = DB::name('SystemConfig')->where('id','in',[2,4,6,7])->column('name,value');

        //        dump($db);die();



        return $this->fetch();

    }



    /* 列表页 */

    public function list()

    {

      

        $id = $this->request->param('id');

        $id = empty($id) ? 0 : $id;

        $this->assign('catId', $id);





        //获得栏目模板信息

        $articleCate = DB::name('DataArticleCate')->where(["id" => $id])->find();  //分类信息

        $this->assign('catInfo', $articleCate);     //当前分类信息



        if (empty($articleCate['link_name'])) {

            $articleCate['link_name'] = "List";

        }

        $this->assign('linkName', $articleCate['link_name']);     //当前分类的静态名称



        if ($articleCate['parent_id'] == 0 && empty($articleCate['content_template_id'])) {

            //如果是顶级栏目

            $catIds = Db::name('DataArticleCate')->where(['parent_id' => $id])->column('id');

            if (empty($catIds[0])) {

                dump("此分未设置内容模板或下级分类！");

                die();

            }

            $childCate = DB::name('DataArticleCate')->where(["id" => $catIds[0]])->find();  //第一个分类信息



            //获得指定栏目所在的所有同级栏目

            $this->assign('catTreeList', $GLOBALS['function']->getCatList($catIds[0]));



            $templateInfo = Db::name('DataTemplate')->where(["id" => $childCate['template_id']])->find();        //分模板信息



            $contentTemplateInfo = Db::name('DataTemplate')->where(["id" => $childCate['content_template_id']])->find();        //内容模板信息

            $catIds = implode(",", $catIds); //将数组转成字符串

            $where = "cat_id IN (" . $catIds . ")";

        } else {

            $templateInfo = Db::name('DataTemplate')->where(["id" => $articleCate['template_id']])->find();        //分模板信息

            $contentTemplateInfo = Db::name('DataTemplate')->where(["id" => $articleCate['content_template_id']])->find();        //内容模板信息

            $where['cat_id'] = $id;



            //获得指定栏目所在的所有同级栏目

            $this->assign('catTreeList', $GLOBALS['function']->getCatList($id));

        }



        $prefix = config("database.connections.mysql.prefix");      //数据表前缀

        if ($articleCate['is_page'] == 1) {

            //如果是单页，获得单页信息并跳转

            $articlePage = DB::table($prefix . $contentTemplateInfo['table_name'])->field("id,cat_id")->where(["cat_id" => $id])->find();  //获得单页信息



            if (empty($articlePage)) {

                dump("此页未创建内容！");

                die();

            }

            $this->redirect("/site-" . $articleCate['link_name'] . "/show-" . $articlePage['cat_id'] . "-" . $articlePage['id'] . ".html");

        }



        //获得每页设置显示数量

        $pageNum = empty($articleCate['page_num']) ? $GLOBALS['function']->getConfig()['page_num'] : $articleCate['page_num'];



        //获得筛选项

        $filterList = [];

        $filterList = DB::table($prefix . "data_template_field")->field("field_name,field_other_name,filed_setting")

            ->where(["template_id" => $articleCate['content_template_id'], "status" => 1, "is_filter" => 1])->select()->toArray();

        foreach ($filterList as $key => $value) {

            $filed_setting = explode("\r\n", $value['filed_setting']);



            foreach ($filed_setting as $k => $v) {

                $filterList[$key]['filter'][$k]['name'] = substr($v, 0, strrpos($v, "|"));

                $filterList[$key]['filter'][$k]['value'] = substr($v, strripos($v, "|") + 1);

            }

        }



        $this->assign('filterList', $filterList);



        //筛选

        $whereGet = [];

        if ($this->request->param('filter') == 1) {

            foreach ($filterList as $key => $value) {

                $fieldName = $value['field_name'];

                if ($this->request->param($fieldName)) {

                    $whereGet[$fieldName] = $this->request->param($fieldName);

                    $this->assign($fieldName, $this->request->param($fieldName));

                    if (empty($this->request->param($fieldName))) {

                        unset($whereGet[$fieldName]);

                    }

                }

            }

        }



        //指定栏目的文章列表

        $list = DB::table($prefix . $contentTemplateInfo['table_name'])

            ->where($where)->where($whereGet)->where(['status' => 1])->order('sort desc,id desc')

            ->paginate(['list_rows' => $pageNum, 'query' => request()->param()])->each(function ($item, $key) {

                //循环操作

                return $item;

            });

        $page = $list->render();

        $this->assign('page', $page);

        $this->assign('articleList', $list);



        //获得列表页模板

        $template = substr($templateInfo['file_name'], 0, strrpos($templateInfo['file_name'], "."));

        

        //产品分类

        $this->product_cats = Db::table('store_goods_cate')->order('sort desc')->where('status',1)->where('parent_id',0)->field('id,icon,title')->select();
     

        //分类id

        $this->cat_id = $this->request->param('cat_id',0);

        $this->child_id = $this->request->param('child_id',0);

        $this->third_id = $this->request->param('third_id',0);

        if($this->cat_id > 0){

            $this->product_cats_childs = Db::table('store_goods_cate')->where('parent_id',$this->cat_id)->order('sort desc')->where('status',1)->field('id,icon,title')->select();

        }

        if($this->child_id > 0){

            $this->product_cats_third = Db::table('store_goods_cate')->where('parent_id',$this->child_id)->order('sort desc')->where('status',1)->field('id,icon,title')->select();

        }

        $where_goods = [];

        $where_goods[] = ['status','=',1];



        $categoryIds = [];

        // 计算最终分类ID

        if ($this->third_id > 0) {

            // **优先使用 `third_id`，忽略 `child_id` 和 `cat_id`**

            $categoryIds[] = $this->third_id;

        } elseif ($this->child_id > 0) {

            // **如果 `third_id` 为空，才使用 `child_id`**

            $categoryIds[] = $this->child_id;

            $categoryIds = array_merge($categoryIds, $this->getChildCategories($this->child_id));

        } elseif ($this->cat_id > 0) {

            // **如果 `third_id` 和 `child_id` 都为空，才使用 `cat_id`**

            $categoryIds[] = $this->cat_id;

            $categoryIds = array_merge($categoryIds, $this->getChildCategories($this->cat_id));

        }

    

        // 去重

        $categoryIds = array_unique($categoryIds);

    

        // 去重

        $categoryIds = array_unique($categoryIds);



        if( count($categoryIds)){

            $where_goods[] = ['cate_id','in',$categoryIds];

        }

        $page = $this->request->param('page',1);

        $this->page = $page;

        $this->goods_list = StoreGoods::where($where_goods)->order('sort desc,id desc')->field('id,cate_id,title,logo')->page($page,6)->select();

        $this->gooods_count = StoreGoods::where($where_goods)->count();

        // $this->spec_list = GoodsAttribute::with(['values'])->select()->toArray();

        $this->goods_cate = Db::table('store_goods_cate')->where('status',1)->where('is_deleted',0)->select();



        $product_select = request()->get();
     

        $this->product_select = $product_select;

        if(count($product_select)){

            $this->product_select_key = array_keys($product_select);

            $this->product_select_value = array_values($product_select);

        }

        // dump($product_select);die;

        if($template == 'list_select'){

            $GoodsAttributeWhere  = [];

            $goods_cate_3 = request()->get('goods_cate_3',0);
            $this->goods_cate_3 = $goods_cate_3;
            $this->goods_cate_2 = request()->get('goods_cate_2',0);
            $this->goods_cate_1 = request()->get('goods_cate_1',0);
           
            if($goods_cate_3 > 0){

                $GoodsAttributeWhere[] = ['cate_id','=',$goods_cate_3];
                
            }
            if($this->goods_cate_1 > 0){
                $this->goods_cate_2_list =  ModelGoodsCate::where('parent_id',$this->goods_cate_1)->select();
            }

            if($this->goods_cate_2 > 0){
                $this->goods_cate_3_list =  ModelGoodsCate::where('parent_id',$this->goods_cate_2)->select();
            }

            $this->goods_cate_id = $goods_cate_3;

            if(count($GoodsAttributeWhere)){
                $this->spec_list = GoodsAttribute::with(['values'])->where($GoodsAttributeWhere)->select()->toArray();
            }else{
                $this->spec_list  = [];
            }
           
        

            $this->goods_cate = Db::table('store_goods_cate')->where('status',1)->where('parent_id',0)->select();

            $userID = $this->app->session->get('uid');

            if(empty($userID)){

                return $this->redirect('/login');

              }

              $cate_goods_ids = [];

              if($goods_cate_3 > 0){

                  $goods_cate_ids = $this->getCategoryIds($goods_cate_3);

                  if(count($goods_cate_ids)){

                      $cate_goods_ids = StoreGoods::where('cate_id','in',$goods_cate_ids)->column('id');

                  }

              }

              

            $product_where = [];

            $spec_select = array_filter($product_select, function ($value, $key) {

                return is_numeric($key) && !empty($value);

            }, ARRAY_FILTER_USE_BOTH);

            $attributeIds = array_keys($spec_select);

            

            if(count($attributeIds)){

                $product_where[] = ['attribute_id','in',$attributeIds];

            }
            $conditions  = $spec_select;
            // dump($conditions);die;
            $product_goods_id = [];
            if(empty($conditions)){

                $product_goods_id =  GoodsAttributeRelations::column('model_id');

            }else{
                // 查询 attribute 表，获取每个 attribute_id 的类型
                $attributeTypes = Db::name('goods_attribute')
                ->whereIn('id', array_keys($conditions))
                ->column('type', 'id');
                    // 初始化查询
                    $query = Db::name('goods_attribute_relations');
                    // 遍历条件，动态构建查询
                    foreach ($conditions as $attribute_id => $value) {
                    $type = $attributeTypes[$attribute_id] ?? 'select'; // 默认类型为 select

                    $query->whereOr(function ($query) use ($attribute_id, $value, $type) {
                        if ($type === 'select') {
                            // select 类型：精确匹配
                            $query->where('attribute_id', $attribute_id)
                                ->where('value', $value);
                        } elseif ($type === 'input') {
                            // input 类型：模糊匹配
                            $query->where('attribute_id', $attribute_id)
                                ->where('value', 'LIKE', "%{$value}%");
                        } elseif ($type === 'checkbox') {
                            $values = explode(',', $value); // 将字符串转换为数组
                            if (is_array($values) && count($values) > 0) {
                                // 使用 whereOr 和 FIND_IN_SET 查询
                                foreach ($values as $val) {
                                    $query->whereOrRaw("FIND_IN_SET(?, value)", [$val]);
                                }
                            } else {
                                // 如果 $values 不是数组，直接使用 FIND_IN_SET 查询
                                $query->whereRaw("FIND_IN_SET(?, value)", [$values]);
                            }
                        }
                    });
                    }
                    
                    // 分组并筛选出满足所有条件的 model_id
                    $product_goods_id = $query->group('model_id')
                            ->having('COUNT(*) = ' . count($conditions))
                            ->column('model_id');
            }
            
                  
            // foreach ($spec_select as $key => $value) {

            //     $goods_attribute = GoodsAttribute::find($key);

            //     if($goods_attribute->type == 'input'){

            //         $product_where_or[] = ['value','like',"%{$value}%"];

            //     }

            //     if($goods_attribute->type == 'select'){

            //         $product_where_or[] = ['value','=',$value];

            //     }

            //     if($goods_attribute->type == 'cahcbox'){

                   

            //     }

            // }
         
          

            // $product_goods_id = GoodsAttributeRelations::where($product_where)->whereOr($product_where_or)->column('model_id');

           
            $product_goods_id_arr = [];
            if(count($product_goods_id)){

                $product_goods_id_arr = array_unique($product_goods_id);

            }

            $goods_model_where = [];

            // if(count($product_goods_id_arr)){

            //     $goods_model_where[] = ['id','in',$product_goods_id_arr];

            // }

            $goods_model_where[] = ['id','in',$product_goods_id_arr];

     

            if(!count($attributeIds) && ($goods_cate_3) > 0){

              

                $goods_model_where[] = ['id','in',$cate_goods_ids];

            }

           

            $goods_model_page  = $this->request->param('page/d',1);

            $goods_models = GoodsModels::with(['goods'])->where($goods_model_where)->page($goods_model_page,5)->select();

            if(count($goods_models)){

                foreach ($goods_models as $key => &$model) {

                    $attributes = $model->attributes()->with(['attribute', 'attribute_value'])->select();

                    foreach ($attributes as $attribute) {
                        if(isset($attribute->attribute->type) &&  $attribute->attribute->type == 'checkbox'){
                            $realtions_value = GoodsAttributeRelations::where('model_id',$model->id)->where('attribute_id',$attribute->attribute_id)->value('value');
                            $realtions_value_text = GoodsAttributeValue::where('id','in',$realtions_value)->column('value');
                            $attribute->attribute_value = is_array($realtions_value_text) ?  implode(',',$realtions_value_text) : [];
                        }

                        $attribute_info = [

                            'name'  => $attribute->attribute->name ?? '未知属性',

                            'value' => null,

                            'sort'  => 0

                        ];

    

                        if ($attribute->attribute) {

                            if ($attribute->attribute->type === 'input') {

                                $attribute_info['value'] = $attribute->value ?? '未设置';

                            } elseif ($attribute->attribute->type === 'select') {

                                $attribute_info['value'] = $attribute->attribute_value->value ?? '未选择';

                            }elseif ($attribute->attribute->type === 'checkbox') {

                                $attribute_info['value'] =  $attribute->attribute_value ? $attribute->attribute_value : '未选择';

                            }
                            $attribute_info['sort']   = $attribute->attribute->sort ?? 0;
                        }

    

                        $model_attributes[] = $attribute_info;

                    }

                    $model->attributes_info = $model_attributes;

                }

            }

            $this->goods_models = $goods_models;

            // dump($this->goods_models->toArray());die;

            $this->goods_model_page = $goods_model_page;

            $this->goods_model_count = GoodsModels::where($goods_model_where)->count(); 

        }



        return $this->fetch($template);

    }

    //获取下级分类
    public function get_second_category(){
        $id = $this->request->param('parent_id');
        $child_cate = Db::table('store_goods_cate')->where('parent_id',$id)->where('status',1)->select();
        return $this->success('ok',$child_cate);
    }

       // 递归获取所有下级分类ID

    protected function getChildCategories($parentId) {

        $ids = Db::table('store_goods_cate')

            ->where('parent_id', $parentId)

            ->where('status', 1)

            ->where('is_deleted', 0)

            ->column('id'); // 只获取 ID

        foreach ($ids as $id) {

            $ids = array_merge($ids, $this->getChildCategories($id)); // 递归查找

        }

        return $ids;

    }



    // 递归获取所有上级分类ID

    protected function getParentCategories($categoryId, &$parents = []) {

        $parent = Db::table('store_goods_cate')

            ->where('id', $categoryId)

            ->where('is_deleted', 0)

            ->value('parent_id');

        if ($parent && $parent != 0) {

            $parents[] = $parent;

            $this->getParentCategories($parent, $parents);

        }

        return $parents;

    }



    function getCategoryIds($id, &$ids = []) {

        // 先把自身 ID 加入

        $ids[] = $id;

    

        // 查询所有子分类

        $children = Db::name('store_goods_cate')

            ->where('parent_id', $id)

            ->where('is_deleted', 0) // 过滤已删除

            ->column('id');

    

        // 递归查询子分类

        foreach ($children as $childId) {

            $this->getCategoryIds($childId, $ids);

        }

    

        return $ids;

    }



    protected function goods_spec_detail($model_ids = [])

        {

           



            if (empty($model_ids)) {

                return [];

            }



            // 查询所有型号

            $models = GoodsModels::where('id', 'in', $model_ids)->select();



            if ($models->isEmpty()) {

                return $this->error('规格未找到');

            }



            // 处理每个型号的属性信息

            $models_info = [];

            foreach ($models as $model) {

                $model_attributes = [];



                // 获取该型号的所有属性

                $attributes = $model->attributes()->with(['attribute', 'attribute_value'])->select();



                foreach ($attributes as $attribute) {

                    $attribute_info = [

                        'name'  => $attribute->attribute->name ?? '未知属性',

                        'value' => null

                    ];



                    if ($attribute->attribute) {

                        if ($attribute->attribute->type === 'input') {

                            $attribute_info['value'] = $attribute->value ?? '未设置';

                        } elseif ($attribute->attribute->type === 'select') {

                            $attribute_info['value'] = $attribute->attribute_value->value ?? '未选择';

                        }

                    }



                    $model_attributes[] = $attribute_info;

                }



                $model->attributes_info = $model_attributes;

                $models_info[] = $model;

            }

            return $models_info;

        }





    /* 详情页/单页 */

    public function show()

    {

        

        $id = $this->request->param('id');      //获得路由传送参数

        $id = empty($id) ? 0 : $id;

        $this->assign('id', $id);



        $catId = $this->request->param('cat_id');

        $catId = empty($catId) ? 0 : $catId;

        $this->assign('catId', $catId);





        //获得指定栏目所在的所有同级栏目(左侧树状列表)

        $this->assign('catTreeList', $GLOBALS['function']->getCatList($catId));

        //        dump($GLOBALS['function']->getCatList($catId));die();



        //获得当前图文所属的栏目信息

        $articleCate = DB::name('DataArticleCate')->where(["id" => $catId])->find();  //分类信息

        $this->assign('catInfo', $articleCate);     //当前分类信息



        if (empty($articleCate['link_name'])) {

            $articleCate['link_name'] = "List";

        }

        $this->assign('linkName', $articleCate['link_name']);     //当前分类的静态名称



        $templateInfo = DB::name('DataTemplate')->where(["id" => $articleCate['template_id']])->find();        //分类模板信息

        $contentTemplateInfo = DB::name('DataTemplate')->where(["id" => $articleCate['content_template_id']])->find();        //内容模板信息



        if (!$contentTemplateInfo['table_name']) {

            return $this->fetch("error_page");

            exit;

        }



        //获得当前图文信息

        $article = Db::name($contentTemplateInfo['table_name'])->where('id', $id)->find();

        foreach ($article as $k => $v) {

            if (!empty($v) && strpos($v, "|") !== false && !in_array($k, ['title', 'subtitle', 'content', 'keywords'])) {

                //处理字段内是否有“|”符号，如果有则拆分成数组

                $article[$k] = explode("|", $v);

            }

        }

        if (!empty($article['associated'])) {

            $associated = json_decode($article['associated'], true);

            $article['associatedList'] = Db::name($associated['tableName'])

                ->where('id', 'IN', $associated['id'])->order('sort desc,id desc')

                ->select()->toArray();

        } else {

            $article['associatedList'] = [];

        }

        $this->assign('article', $article);







        $prefix = config("database.connections.mysql.prefix");      //数据表前缀

        //浏览次数+1

        Db::table($prefix . $contentTemplateInfo['table_name'])->where('id', $id)->Inc('read_count', 1)->update();



        //上一篇图文信息

        $prev_article = $GLOBALS['function']->getArticlePrev($article['id'], $articleCate['id'], $contentTemplateInfo['table_name']);

        $this->assign('prev', $prev_article);



        //下一篇图文信息

        $next_article = $GLOBALS['function']->getArticleNext($article['id'], $articleCate['id'], $contentTemplateInfo['table_name']);

        $this->assign('next', $next_article);



        //获得列表页模板

        $template = substr($contentTemplateInfo['file_name'], 0, strrpos($contentTemplateInfo['file_name'], "."));



        return $this->fetch($template);

    }



    /* 搜索内容列表 */

    public function search()

    {

        $keyword = $this->request->param('keyword') ?? $this->app->session->get('keyword');

        $this->app->session->set('keyword', $keyword);

        $this->assign('keyword', $keyword);

        $pageNum = $GLOBALS['function']->getConfig()['page_num'];    //获得每页设置显示数量

        $prefix = config("database.connections.mysql.prefix");      //数据表前缀

        $modelName = "";

        if (!isset($_GET['model']) || (isset($_GET['model']) && empty($_GET['model']))) {

            //如果没有模型选择，则搜索全部模型

            $tables = DB::query("show tables like 'data_article_show_%'");  //搜索所有内容模型数据表



            foreach ($tables as $key => $value) {

                //将所有获得的数据表数组整理成一维数组

                if (array_values($value)[0] != 'data_article_show_default') {

                    //去除默认模型

                    $tableArr[] = array_values($value)[0];

                }

            }

           

            $whereField = "id,cat_id,title,subtitle,create_at,logo,keywords,force_link,template_id";       //获得字段

            $whereUnion = [];

     

            foreach ($tableArr as $key => $value) {

                //生成与union关联的查询语句

                if($value != 'data_article_show_no'){

                    $whereUnion[] = DB::table($prefix . $value)->alias("a")->field($whereField)->where('title LIKE "%' . $keyword . '%" AND status = 1')->buildSql();

                }

            }

            // $whereUnion[] = DB::table('store_goods')->alias("a")->field('id,cate_id,title,create_at,logo')->where('title LIKE "%' . $keyword . '%" AND status = 1')->buildSql();

            //生成union子查询语句

            $sqlUnion = DB::table($prefix . "data_article_show_default")->alias("a")->field($whereField)

                ->where('title LIKE "%' . $keyword . '%" AND status = 1')

                ->union($whereUnion)->buildSql();

     

            //获得搜索结果

            $list = DB::table($sqlUnion)->alias("a")

                ->paginate($pageNum, false, ['query' => request()->param()])->each(function ($item, $key) {

                    //循环操作

                    return $item;

                });

        } else {

            //如果有模型选择，则搜索该模型

            $modelName = $_GET['model'];

            $templateInfo = DB::name('DataTemplate')->where(["template_name" => $modelName, 'template_type' => 1])->find();        //内容模型信息

            $tableName = $templateInfo['table_name'];

            if($modelName == '产品'){

                $tableName = 'store_goods';

            }

            //获得搜索结果

            $list = DB::table($prefix . $tableName)

                ->where('title LIKE "%' . $keyword . '%"')->where(['status' => 1])->order('sort desc,id desc')

                ->paginate($pageNum, false, ['query' => request()->param()])->each(function ($item, $key) {

                    //循环操作

                    return $item;

                });

            

            

        }



        $page = $list->render();

        $this->assign('page', $page);

        $this->assign('articleList', $list);



        $this->assign('modelName', $modelName);



        return $this->fetch('search');

    }

  /**

     * 表单提交处理

     */

    public function select_list()

    {

        

        return $this->fetch();

}

    /**

     * 表单提交处理

     */

    public function form_handle()

    {



        //接收表单提交

        if (request()->isPost()) {

            $data = $_POST;



            if (empty(trim($data['name']))) {

                $this->error("请填写您的姓名");

            }

            if (empty(trim($data['phone']))) {

                $this->error("请填写您的电话");

            }



            $member_id = 0;        //如果用户登陆，则获得用户ID



            //获得访问用户的IP

            $ip = $_SERVER['REMOTE_ADDR'];

            if (isset($_SERVER['HTTP_CLIENT_IP']) && preg_match('/^([0-9]{1,3}\.){3}[0-9]{1,3}$/', $_SERVER['HTTP_CLIENT_IP'])) {

                $ip = $_SERVER['HTTP_CLIENT_IP'];

            } elseif (isset($_SERVER['HTTP_X_FORWARDED_FOR']) and preg_match_all('#\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}#s', $_SERVER['HTTP_X_FORWARDED_FOR'], $matches)) {

                foreach ($matches[0] as $xip) {

                    if (!preg_match('#^(10|172\.16|192\.168)\.#', $xip)) {

                        $ip = $xip;

                        break;

                    }

                }

            }



            $ifThere = Db::name("DataFormList")->where(['member_id' => $member_id, 'member_IP' => $ip, 'type' => $data['type'], 'is_status' => 1])->count("id");

            if ($ifThere > 0) {

                $this->error("您留言正在审核中，请不要重复提交！", '');

            } else {

                $mailTitle = "Welcome to UNICARBON";



                Index::send_mail($data['email'], $data['name'], $mailTitle);



                Db::name('DataFormList')->insert([

                    'member_id' => $member_id,

                    'name' => $data['name'],

                    'phone' => $data['phone'],

                    //                    'email' => $data['email'],

                    'text_desc' => $data['text_desc'],

                    'type' => $data['type'],

                    'member_IP' => $ip,

                    'is_status' => 1,

                    'is_deleted' => 0

                ]);

                $this->success("提交成功！", '');

            }

        }

    }

}

